<template lang="pug">
.view.cp-inv-assembly.fix-flex-pos
  //- 查询
  el-form.ass-search(:inline="true")
    el-form-item
      el-select.select-width(v-model="timeType", placeholder="请选择")
        el-option(key="0", label="创建时间", :value="0")
        el-option(key="1", label="更新时间", :value="1")
        el-option(key="2", label="组装拆卸时间", :value="2")
    el-form-item(label="起止时间 :")
      el-date-picker.date-width(
        v-model="dateRange",
        type="daterange",
        unlink-panels,
        start-placeholder="开始日期",
        end-placeholder="结束日期",
        value-format="timestamp",
        :default-time="['00:00:00', '23:59:59']")
    el-form-item(label="状态 :")
      el-select.select-width(v-model="status", placeholder="请选择")
        el-option(label="全部", :value="null")
        el-option(
          v-for="(item, index) in allAssemblyStatus",
          :key="index",
          :label="item.name",
          :value="item.value")
    el-form-item(label="类型 :")
      el-select.select-width(v-model="assemdisassemblyType", placeholder="请选择")
        el-option(label="全部", :value="null")
        el-option(
          v-for="(item, index) in allAssemblyType",
          :key="index",
          :label="item.name",
          :value="item.value")
    el-form-item(label="源头仓库 :")
      el-select.select-width(v-model="sourceStorehouse", placeholder="请选择")
        el-option(label="全部", :value="null")
        el-option(
          v-for="(item, index) in allStorehouse",
          :key="index",
          :label="item.name",
          :value="item.value")
    el-form-item(label="目的仓库 :")
      el-select.select-width(v-model="targetStorehouse", placeholder="请选择")
        el-option(label="全部", :value="null")
        el-option(
          v-for="(item, index) in allStorehouse",
          :key="index",
          :label="item.name",
          :value="item.value")
    el-form-item(label="仓管员 :")
      el-select.select-width(v-model="keeper", placeholder="请选择")
        el-option(label="全部", :value="null")
        el-option(
          v-for="(item, index) in allKeeper",
          :key="index",
          :label="item.name",
          :value="item.value")
    el-form-item
      el-input(
        v-model="orderNo",
        placeholder="组装拆卸单号",
        suffix-icon="el-icon-search"
        style="width: 320px")
    el-form-item(label="关键字 :")
      el-input(
        v-model="keyWord",
        placeholder="关键字",
        style="width: 160px")
    el-form-item
      el-button(type="primary", @click="search") 搜索
    el-form-item
      el-button(type="primary", @click="creatAssemblyBill", plain) 新建组拆单
    el-form-item
      el-button(@click="exportReport", plain) 导出
  //- 表格
  .ass-table
    el-table(
      :data="invAssemblyList",
      highlight-current-row,
      v-loading="loadingAssembly",
      @row-dblclick="dbClickRow",
      size="mini",
      height="100%")
      el-table-column(show-overflow-tooltip, type="index", :index="indexMethod", label="序号")
      el-table-column(label="单号")
        template(slot-scope="scope")
          el-tooltip(
            effect="dark"
            placement="top"
            :content="scope.row.orderNo")
            div.cell.el-tooltip(style="padding: 0") {{scope.row.orderNo}}
      el-table-column(show-overflow-tooltip, prop="status", label="状态")
        template(slot-scope="scope")
          span {{ scope.row.status | compare-list(allAssemblyStatus) }}
      el-table-column(show-overflow-tooltip, label="组装拆卸时间", min-width="90px")
        template(slot-scope="scope")
          span {{scope.row.assemdisassemblyTime | date-format}}
      el-table-column(show-overflow-tooltip, prop="assemdisassemblyType", label="类型")
        template(slot-scope="scope")
          span {{ scope.row.assemdisassemblyType | compare-list(allAssemblyType) }}
      el-table-column(show-overflow-tooltip, prop="sourceStorehouse", label="源头仓库")
        template(slot-scope="scope")
          span {{ scope.row.sourceStorehouse | compare-list(allStorehouse) }}
      el-table-column(show-overflow-tooltip, prop="targetStorehouse", label="目的仓库")
        template(slot-scope="scope")
          span {{ scope.row.targetStorehouse | compare-list(allStorehouse) }}
      el-table-column(show-overflow-tooltip, prop="nextInboundOrder", label="关联入库单")
      el-table-column(show-overflow-tooltip, prop="nextOutboundOrder", label="关联出库单")
      el-table-column(show-overflow-tooltip, prop="keeper", label="仓管员")
        template(slot-scope="scope")
          span {{ scope.row.keeper | compare-list(allKeeper) }}
      el-table-column(show-overflow-tooltip, label="创建时间")
        template(slot-scope="scope")
          span {{scope.row.creationTime | date-format}}
      el-table-column(show-overflow-tooltip, prop="remark", label="备注")
      el-table-column(label="操作", min-width="110px")
        template(slot-scope="scope")
          el-tooltip(content="查看")
            i.icon-act.el-icon-view(@click="viewInvAssembly(scope.row)")
          el-tooltip(content="编辑")
            i.icon-act.el-icon-edit(@click="editInvAssembly(scope.row)")
          el-tooltip(content="复制")
            i.icon-act.el-icon-hy-copy(@click="copyInvAssembly(scope.row)")
          el-dropdown
            i.icon-act.el-icon-more
            el-dropdown-menu(slot="dropdown", class="inv-act-drop")
              el-dropdown-item.act-item(@click.native="submitInvOrder(scope.row)")
                i.icon-act.el-icon-hy-submit-o
                span 提交
              el-dropdown-item.act-item(@click.native="backInvOrder(scope.row)")
                i.icon-act.el-icon-hy-back
                span 撤回
              el-dropdown-item.act-item(@click.native="deleteInvOrder(scope.row, scope.$index)")
                i.icon-act.el-icon-delete
                span 删除
              el-dropdown-item.act-item(@click.native="printInvOrder(scope.row)")
                i.icon-act.el-icon-hy-print
                span 打印
  //- 分页
  el-pagination.ass-pagination(
    background,
    layout="total, prev, pager, next, jumper",
    prev-text="上一页",
    next-text="下一页",
    @current-change="handleCurrentChange",
    :current-page="pageNum",
    :page-size="pageSize",
    :total="totalNum")
  //- 新建组装拆卸单
  assemblyForm(
    :title="assemblyDialogTitle",
    :visible.sync="showAssemblyDialog",
    :is-edit="isEdit",
    :parent-data="formData",
    @submit="onFormSubmit",
    @close="showAssemblyDialog = false")
</template>

<script>
import { mapGetters } from 'vuex';
import ComApi from '@/api/common';
import AssemblyApi from '@/api/inventory/inbound';
import assemblyForm from './assemblyForm';

export default {
  name: 'invassembly',
  data() {
    return {
      loadingAssembly: true,
      invAssemblyList: [],
      pageNum: 1,
      pageSize: 20,
      totalNum: 0,
      // 搜索条件
      timeType: 0,
      dateRange: [],
      status: null,
      assemdisassemblyType: null,
      sourceStorehouse: null,
      targetStorehouse: null,
      keeper: null,
      orderNo: null,
      keyWord: null,
      // 弹出框
      assemblyDialogTitle: '新建组装拆卸单',
      showAssemblyDialog: false,
      // 能编辑  true--能 false--不能
      isEdit: true,
      // 新建时初始数据
      formData: {
        assemdisassemblyTime: new Date(),
        sourceSKUArray: [{ canEdit: false }],
        targetSKUArray: [{ canEdit: false }]
      },
      // 搜索下拉框
      allAssemblyStatus: [],
      allAssemblyType: []
    };
  },
  computed: {
    ...mapGetters({
      creator: 'employeeId',
      allStorehouse: 'storeSelect',
      allKeeper: 'keeperSelect'
    })
  },
  components: {
    assemblyForm
  },
  created () {
    // 状态列表
    ComApi.getStatus({ orderType: 'assemdisassembly' }).then((statusList) => {
      this.allAssemblyStatus = statusList;
    });
    // 类别列表
    ComApi.getTypes({ orderType: 'assemdisassembly' }).then((typeList) => {
      this.allAssemblyType = typeList;
    });
  },
  mounted() {
    this.loadAssemblyList();
  },
  methods: {
    indexMethod (i) {
      return ((this.pageNum - 1) * this.pageSize) + (i + 1);
    },
    filterParams() {
      const params = {
        creator: this.creator,
        status: this.status,
        assemdisassemblyType: this.assemdisassemblyType,
        sourceStorehouse: this.sourceStorehouse,
        targetStorehouse: this.targetStorehouse,
        keeper: this.keeper,
        orderNo: this.orderNo,
        keyWord: this.keyWord,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };
      if (this.timeType === 0 && this.dateRange && this.dateRange[0]) {
        params.startCreationTime = this.dateRange[0];
        params.endCreationTime = this.dateRange[1];
      }
      if (this.timeType === 1 && this.dateRange && this.dateRange[0]) {
        params.startUpdateTime = this.dateRange[0];
        params.endUpdateTime = this.dateRange[1];
      }
      if (this.timeType === 2 && this.dateRange && this.dateRange[0]) {
        params.startAssemblyDisassemblyTime = this.dateRange[0];
        params.endAssemblyDisassemblyTime = this.dateRange[1];
      }
      for (const key in params) {
        if (params[key] === null || params[key] === '') {
          delete params[key];
        }
      }
      return params;
    },
    // 取得调拨数据
    loadAssemblyList() {
      this.loadingAssembly = true;
      const params = this.filterParams();
      AssemblyApi.getAssemblyList(params).then((result) => {
        if (result.status === 0 && result.obj) {
          this.invAssemblyList = result.obj.records;
          this.totalNum = result.obj.totalNum;
        } else {
          this.$message.error(result.comment || '获取数据失败');
        }
        this.loadingAssembly = false;
      }).catch((error) => {
        this.loadingAssembly = false;
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 搜索
    search() {
      if (this.pageNum !== 1) {
        this.pageNum = 1;
      }
      this.loadAssemblyList();
    },
    // 新建
    creatAssemblyBill() {
      this.assemblyDialogTitle = '新建组装拆卸单';
      this.formData = {
        orderNo: null,
        keeper: null,
        assemdisassemblyType: null,
        demander: null,
        demand1LevelDept: null,
        demand2LevelDept: null,
        sourceStorehouse: null,
        targetStorehouse: null,
        assemdisassemblyTime: new Date(),
        nextInboundOrder: null,
        nextOutboundOrder: null,
        remark: null,
        sourceSKUArray: [{ canEdit: true }],
        targetSKUArray: [{ canEdit: true }]
      };
      this.showAssemblyDialog = true;
      this.isEdit = true;
    },
    dbClickRow(currentrow) {
      this.viewInvAssembly(currentrow);
    },
    // 查看
    viewInvAssembly(currentrow) {
      this.assemblyDialogTitle = '查看组装拆卸单';
      const params = {
        orderNo: currentrow.orderNo
      };
      AssemblyApi.detailInvAssembly(params).then((res) => {
        if (res.status === 0 && res.obj) {
          this.formData = {
            ...res.obj,
            orderNo: currentrow.orderNo
          };
          this.showAssemblyDialog = true;
          this.isEdit = false;
        } else {
          this.$message.error(res.comment || '获取详情失败');
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 日期生成Date对象
    filterDate(data = []) {
      if (!data) {
        return [];
      }
      return data.map((item) => {
        if (item.productionDate) {
          const productionDate = new Date(item.productionDate).getTime();
          return { ...item, productionDate };
        }
        return item;
      });
    },
    // 编辑
    editInvAssembly(currentrow) {
      this.assemblyDialogTitle = '编辑组装拆卸单';
      const params = {
        orderNo: currentrow.orderNo
      };
      AssemblyApi.detailInvAssembly(params).then((res) => {
        if (res.status === 0 && res.obj) {
          this.formData = {
            ...res.obj,
            orderNo: currentrow.orderNo,
            assemdisassemblyTime: new Date(res.obj.assemdisassemblyTime),
            sourceSKUArray: this.filterDate(res.obj.sourceSKUArray),
            targetSKUArray: this.filterDate(res.obj.targetSKUArray)
          };
          this.showAssemblyDialog = true;
          this.isEdit = true;
        } else {
          this.$message.error(res.comment || '获取详情失败');
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 复制
    copyInvAssembly(currentrow) {
      this.assemblyDialogTitle = '新建组装拆卸单';
      const params = {
        orderNo: currentrow.orderNo
      };
      AssemblyApi.detailInvAssembly(params).then((res) => {
        if (res.status === 0 && res.obj) {
          this.formData = {
            ...res.obj,
            orderNo: null,
            assemdisassemblyTime: new Date(res.obj.assemdisassemblyTime),
            sourceSKUArray: this.filterDate(res.obj.sourceSKUArray),
            targetSKUArray: this.filterDate(res.obj.targetSKUArray)
          };
          this.showAssemblyDialog = true;
          this.isEdit = true;
        } else {
          this.$message.error(res.comment || '获取详情失败');
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 保存提交成功
    onFormSubmit(data) {
      if (data.isNew) {
        // 新增
        this.invAssemblyList.unshift({});
        this.$set(this.invAssemblyList, 0, data);
        this.totalNum = this.totalNum + 1;
      } else {
        const index = this.invAssemblyList.findIndex(item => item.orderNo === data.orderNo);
        this.$set(this.invAssemblyList, index, data);
      }
    },
    // 导出
    exportReport() {
      console.log('导出exportReport');
    },
    // 页码改变
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.loadAssemblyList();
    },
    // 提交
    submitInvOrder(currentRow) {
      const params = {
        orderNo: currentRow.orderNo
      };
      AssemblyApi.submitInvAssembly(params).then((res) => {
        if (res.status === 0) {
          this.$message({ message: '提交成功', type: 'success' });
          currentRow.status = res.obj;
        } else {
          this.$message.error(res.comment || '提交失败');
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 撤回
    backInvOrder(currentRow) {
      const params = {
        orderNo: currentRow.orderNo
      };
      AssemblyApi.backInvAssembly(params).then((res) => {
        if (res.status === 0) {
          this.$message({ message: '撤回成功', type: 'success' });
          currentRow.status = res.obj;
        } else {
          this.$message.error(res.comment || '撤回失败');
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 删除
    deleteInvOrder(currentRow, index) {
      this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          orderNo: currentRow.orderNo
        };
        AssemblyApi.deleteInvAssembly(params).then((res) => {
          if (res.status === 0) {
            this.invAssemblyList.splice(index, 1);
            this.totalNum = this.totalNum - 1;
            this.$message({ message: '删除成功', type: 'success' });
          } else {
            this.$message.error(res.comment || '删除失败');
          }
        });
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' });
      });
    },
    // 打印
    printInvOrder(currentRow) {
      console.log('print', currentRow);
    }
  }
};
</script>

<style lang="sass">
@import "../../../styles/utils"
$SEARCHHEIGHT: 104px
$SELECTWIDTH: 100px
.cp-inv-assembly
  .ass-search
    height: $SEARCHHEIGHT
    padding: 12px 0 12px 16px
    overflow-x: auto
    overflow-y: hidden
    .select-width
      width: $SELECTWIDTH
    .date-width
      width: 260px
    .el-form-item
      margin-right: 14px
    .el-form-item__label
      margin-left: 6px
      padding-right: 6px
    .el-date-editor .el-range__close-icon
      width: 20px
    .el-form-item--small .el-form-item__content, .el-form-item--small .el-form-item__label
      height: 32px
  .ass-table
    position: absolute
    top: $SEARCHHEIGHT
    bottom: 56px
    left: 16px
    right: 16px
    overflow-x: hidden
    overflow-y: auto
    &::before
      display: none
    .icon-act
      font-size: 16px
      font-weight: 500
      cursor: pointer
      margin-left: 3px
      margin-right: 3px
      &:hover
        color: #5D9BFB
  .el-table
    th, td
      text-align: center
  .ass-pagination
    position: absolute
    bottom: 12px
    left: 0
    right: 0
    text-align: center
.inv-act-drop
  .icon-act
    font-size: 16px
    font-weight: 500
    cursor: pointer
    margin-left: -3px
    margin-right: 6px
</style>
